import './index.less'
import { Button } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import createEvent, { useT, request } from '@designable/event-system'
import { Modal, message } from 'antd'
import { ActionType } from '@ant-design/pro-table'
import { ProFormInstance } from '@ant-design/pro-form'
import { useRef } from 'react'
import { FormConsumer } from '@formily/react'
import React, { useState } from 'react'
import EditableProTable from '@ant-design/pro-table'
import { FormCascaderCategory } from '../FormCascaderCategory'
import { useForm } from '@formily/react'
import { useField } from '@formily/react'
import { observer } from '@formily/reactive-react'

type PropsType = {
  addOrEdit: boolean
  confirmExpression: string
}

// 商品品类分页
function productCategoryCategoryProjectPage(params: object) {
  return request({
    uri: '/api/tenant/productCategory/categoryProjectPage',
    params,
    method: 'POST',
  })
}

// 获取品类详情
function productCategoryCategoryProjectDetail(params: {
  categoryId: number | null // 品类ID
}) {
  return request({
    uri: '/api/tenant/productCategory/categoryProjectDetail',
    params,
    method: 'GET',
  })
}

function GoodsCategorySelectComponent(props: PropsType) {
  const { confirmExpression } = props
  const actionRef = useRef<ActionType>()
  const searchRef = useRef<ProFormInstance>()
  const [open, setOpen] = useState(false)
  const $t = useT()
  const [selectRow, setSelectRow] = useState<any>({ categoryId: null })
  const form = useForm() as any
  const field = useField() as any
  const disabled = (field.pattern || field.props.pattern) === 'disabled'

  return (
    <>
      <div className={'categoryWrap'}>
        <FormConsumer>
          {(form) => {
            const { supplierProduct } = form.getFormState().values
            return (
              <>
                <div className={'tableWrap'}>
                  <div className={'label'}>
                    {[
                      $t('品类项目编号'),
                      $t('品类项目名称'),
                      $t('品类名称'),
                      $t('品类类型'),
                      $t('所属类目'),
                      $t('状态'),
                      $t('操作'),
                    ].map((item: any, index: number) => (
                      <div key={index}>{item}</div>
                    ))}
                  </div>
                  {supplierProduct && (
                    <div className={'value'}>
                      {[
                        supplierProduct.categoryProjectCode,
                        supplierProduct.categoryProjectName,
                        supplierProduct.categoryName,
                        supplierProduct.specsTypeDesc
                          ? `${supplierProduct.categoryTypeName} / ${supplierProduct.specsTypeDesc}`
                          : supplierProduct.categoryTypeName,
                        supplierProduct.categoryNameAll,
                        supplierProduct.statusDesc,
                        <Button
                          disabled={disabled}
                          type="link"
                          onClick={() => setOpen(true)}
                        >
                          {$t('更换')}
                        </Button>,
                      ].map((item: any, index: number) => (
                        <div key={index}>{item}</div>
                      ))}
                    </div>
                  )}
                </div>
                {!supplierProduct && (
                  <Button
                    icon={<PlusOutlined />}
                    block
                    onClick={() => {
                      if (!form.values.customerCode) {
                        message.error($t('请先选择客户'))
                        return
                      }
                      setOpen(true)
                    }}
                  >
                    {$t('选择品类')}
                  </Button>
                )}
              </>
            )
          }}
        </FormConsumer>
      </div>
      <Modal
        title={$t('选择品类')}
        width={1200}
        open={open}
        onOk={async () => {
          if (!selectRow.categoryId) {
            message.error($t('请选择'))
            return
          }
          try {
            if (confirmExpression) {
              const detail = await productCategoryCategoryProjectDetail({
                categoryId: selectRow.categoryId,
              })
              await createEvent(confirmExpression as string, {
                form,
                value: { ...selectRow, ...detail },
                $t,
              })
            }
            setOpen(false)
          } catch (e) {
            // eslint-disable-next-line no-console
            console.error('执行确认表达式失败:', e)
          }
        }}
        onCancel={() => {
          setOpen(false)
        }}
        getContainer={() => {
          return (
            document.getElementById('designable-page-wrap') || document.body
          )
        }}
      >
        <EditableProTable
          columns={[
            {
              title: $t('品类项目编号'),
              dataIndex: 'categoryProjectCode',
              search: false,
              ellipsis: true,
            },
            {
              title: $t('品类项目名称'),
              dataIndex: 'categoryProjectName',
              ellipsis: true,
            },
            {
              title: $t('品类名称'),
              dataIndex: 'categoryName',
              ellipsis: true,
            },
            {
              title: $t('品类类型'),
              dataIndex: 'categoryTypeName',
              ellipsis: true,
              valueType: 'treeSelect',
              renderFormItem: () => {
                return <FormCascaderCategory />
              },
              render: (text, record) => {
                void text
                return record.subTypeName
                  ? `${record.categoryTypeName} / ${record.subTypeName}`
                  : record.categoryTypeName
              },
            },
            {
              title: $t('所属类目'),
              dataIndex: 'categoryNameAll',
              ellipsis: true,
              search: false,
            },
            {
              title: $t('状态'),
              dataIndex: 'statusDesc',
              ellipsis: true,
              search: false,
            },
          ]}
          actionRef={actionRef}
          formRef={searchRef}
          tableAlertRender={false}
          rowSelection={{
            type: 'radio',
            defaultSelectedRowKeys: selectRow.categoryId
              ? [selectRow.categoryId]
              : [],
            onChange: (keys, rows) => {
              setSelectRow(rows[0])
            },
          }}
          request={async ({ categoryProjectName, ...params }) => {
            const { customerCode, agreementCode } = form.getFormState().values
            const res = await productCategoryCategoryProjectPage({
              ...params,
              categoryProjectKey: categoryProjectName,
              subCusCode: customerCode,
              agreementCode: agreementCode,
            })
            const { records, total } = res as any
            return {
              data: records,
              success: true,
              total: total,
            }
          }}
          rowKey="id"
          pagination={{
            size: 'default',
            defaultPageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          search={{
            labelWidth: 'auto',
            collapsed: false,
            collapseRender: () => <></>,
            style: {
              background: '#F7F8FA',
              padding: '24px 20px',
              borderRadius: 4,
            },
          }}
          dateFormatter="string"
          toolBarRender={false}
        />
      </Modal>
    </>
  )
}

export const GoodsCategorySelect = observer(GoodsCategorySelectComponent)
